import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../constants/app_colors.dart';
import '../models/thought_record.dart';
import '../services/deepseek_service.dart';
import '../models/database_helper.dart';
import './thought_reshaping_screen.dart';
import 'package:heroicons/heroicons.dart';

class QuestionAnswer {
  final String question;
  final String answer;

  QuestionAnswer({required this.question, required this.answer});
}

class ThoughtReflectionScreen extends StatefulWidget {
  final ThoughtRecord thoughtRecord;

  const ThoughtReflectionScreen({
    Key? key,
    required this.thoughtRecord,
  }) : super(key: key);

  @override
  State<ThoughtReflectionScreen> createState() => _ThoughtReflectionScreenState();
}

class _ThoughtReflectionScreenState extends State<ThoughtReflectionScreen> {
  final _answerController = TextEditingController();
  final List<QuestionAnswer> _questionAnswers = [];
  bool _isLoading = false;
  String? _currentQuestion;
  bool _isCompleted = false;

  @override
  void initState() {
    super.initState();
    _getNextQuestion();
  }

  @override
  void dispose() {
    _answerController.dispose();
    super.dispose();
  }

  Future<void> _getNextQuestion() async {
    if (_isCompleted) return;

    setState(() {
      _isLoading = true;
    });

    try {
      final deepseekService = DeepseekService();
      final question = await deepseekService.getNextQuestion(
        widget.thoughtRecord.thought,
        _questionAnswers.map((qa) => qa.answer).toList(),
      );

      setState(() {
        _currentQuestion = question;
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('获取问题失败: ${e.toString()}')),
      );
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _submitAnswer() async {
    if (_answerController.text.trim().isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入你的回答')),
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      // 保存当前的问题和回答
      if (_currentQuestion != null) {
        _questionAnswers.add(QuestionAnswer(
          question: _currentQuestion!,
          answer: _answerController.text,
        ));
      }
      _answerController.clear();

      if (_questionAnswers.length >= 3) {
        // 生成最终分析
        final deepseekService = DeepseekService();
        final analysis = await deepseekService.generateFinalAnalysis(
          widget.thoughtRecord.thought,
          _questionAnswers.map((qa) => qa.answer).toList(),
        );

        print('Generated final analysis:');
        print('Balanced View: ${analysis['balanced_view']}');
        print('Action Plan: ${analysis['action_plan']}');
        print('Positive Thought: ${analysis['positive_thought']}');

        // 准备更新的数据
        final updatedRecord = widget.thoughtRecord.copyWith(
          reflectionAnswers: _questionAnswers.map((qa) => "${qa.question}|||${qa.answer}").toList(),
          balancedView: analysis['balanced_view'],
          actionPlan: analysis['action_plan'],
          positiveThought: analysis['positive_thought'],
        );

        print('Updating thought record with:');
        print('ID: ${updatedRecord.id}');
        print('Thought: ${updatedRecord.thought}');
        print('Reflection Answers: ${updatedRecord.reflectionAnswers}');
        print('Balanced View: ${updatedRecord.balancedView}');
        print('Action Plan: ${updatedRecord.actionPlan}');
        print('Positive Thought: ${updatedRecord.positiveThought}');

        // 先更新数据库
        if (updatedRecord.id == null) {
          print('Error: Thought record ID is null');
          throw Exception('Thought record ID is null');
        }

        final result = await DatabaseHelper.instance.updateThoughtRecord(updatedRecord);
        print('Database update result: $result');

        if (result <= 0) {
          print('Error: Failed to update thought record in database');
          throw Exception('Failed to update thought record in database');
        }

        // 验证更新是否成功
        final savedRecord = await DatabaseHelper.instance.getThoughtRecord(updatedRecord.id!);
        if (savedRecord == null) {
          print('Error: Failed to retrieve updated thought record');
          throw Exception('Failed to retrieve updated thought record');
        }

        print('Verified saved record:');
        print('ID: ${savedRecord.id}');
        print('Thought: ${savedRecord.thought}');
        print('Reflection Answers: ${savedRecord.reflectionAnswers}');
        print('Balanced View: ${savedRecord.balancedView}');
        print('Action Plan: ${savedRecord.actionPlan}');
        print('Positive Thought: ${savedRecord.positiveThought}');

        // 更新内存中的可变属性
        setState(() {
          widget.thoughtRecord.reflectionAnswers = savedRecord.reflectionAnswers;
          widget.thoughtRecord.balancedView = savedRecord.balancedView;
          widget.thoughtRecord.actionPlan = savedRecord.actionPlan;
          widget.thoughtRecord.positiveThought = savedRecord.positiveThought;
          _isCompleted = true;
        });
      } else {
        await _getNextQuestion();
      }
    } catch (e) {
      print('Error submitting answer: $e');
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('提交回答失败: ${e.toString()}')),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Widget _buildThoughtCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              HeroIcon(
                HeroIcons.cloud,
                size: 24,
                style: HeroIconStyle.solid,
                color: Colors.blueGrey,
              ),
              const SizedBox(width: 8),
              Text(
                '消极想法',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Text(
            widget.thoughtRecord.thought,
            style: GoogleFonts.zcoolKuaiLe(
              fontSize: 18,
              color: AppColors.textPrimary,
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHistoryItem(QuestionAnswer qa) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(
                  color: AppColors.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Center(
                  child: Text(
                    'Q',
                    style: GoogleFonts.zcoolKuaiLe(
                      color: AppColors.primary,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  qa.question,
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                    color: AppColors.textPrimary,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(
                  color: Colors.green.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Center(
                  child: Text(
                    'A',
                    style: GoogleFonts.zcoolKuaiLe(
                      color: Colors.green,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  qa.answer,
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                    color: AppColors.textPrimary,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSection({
    required String title, 
    required String content,
    HeroIcons? icon,  // 添加图标参数
    Color iconColor = Colors.grey,  // 添加图标颜色参数
  }) {
    // 处理行动计划的换行显示
    String formattedContent = content;
    if (title == '行动计划' && content.isNotEmpty) {
      formattedContent = content.replaceAll('。', '。\n');
    }

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: Colors.grey.withOpacity(0.2),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              if (icon != null) ...[
                HeroIcon(
                  icon,
                  size: 24,
                  style: HeroIconStyle.solid,
                  color: iconColor,
                ),
                const SizedBox(width: 8),
              ],
              Text(
                title,
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Text(
            formattedContent,
            style: GoogleFonts.zcoolKuaiLe(
              fontSize: 18,
              color: AppColors.textPrimary,
              height: 1.5,
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _handleDiscardThought() async {
    try {
      await DatabaseHelper.instance.deleteThoughtRecord(widget.thoughtRecord.id!);
      if (!mounted) return;
      Navigator.of(context).pop();
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('删除记录失败: ${e.toString()}')),
      );
    }
  }

  Future<void> _handleSaveThought() async {
    try {
      // 确保所有数据都被正确保存
      final updatedRecord = widget.thoughtRecord.copyWith(
        reflectionAnswers: _questionAnswers.map((qa) => "${qa.question}|||${qa.answer}").toList(),
        balancedView: widget.thoughtRecord.balancedView,
        actionPlan: widget.thoughtRecord.actionPlan,
        positiveThought: widget.thoughtRecord.positiveThought,
      );

      print('Saving thought record with:');
      print('ID: ${updatedRecord.id}');
      print('Thought: ${updatedRecord.thought}');
      print('Reflection Answers: ${updatedRecord.reflectionAnswers}');
      print('Balanced View: ${updatedRecord.balancedView}');
      print('Action Plan: ${updatedRecord.actionPlan}');
      print('Positive Thought: ${updatedRecord.positiveThought}');
      
      // 检查ID是否存在
      if (updatedRecord.id == null) {
        print('Error: Thought record ID is null');
        throw Exception('Thought record ID is null');
      }

      // 先更新数据库
      final result = await DatabaseHelper.instance.updateThoughtRecord(updatedRecord);
      print('Database update result: $result');

      if (result <= 0) {
        print('Error: Failed to update thought record in database');
        throw Exception('Failed to update thought record in database');
      }

      // 验证更新是否成功
      final savedRecord = await DatabaseHelper.instance.getThoughtRecord(updatedRecord.id!);
      if (savedRecord == null) {
        print('Error: Failed to retrieve updated thought record');
        throw Exception('Failed to retrieve updated thought record');
      }

      print('Verified saved record:');
      print('ID: ${savedRecord.id}');
      print('Thought: ${savedRecord.thought}');
      print('Reflection Answers: ${savedRecord.reflectionAnswers}');
      print('Balanced View: ${savedRecord.balancedView}');
      print('Action Plan: ${savedRecord.actionPlan}');
      print('Positive Thought: ${savedRecord.positiveThought}');
      
      if (!mounted) return;
      
      // 导航到想法重塑页面，并清除之前的路由
      Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(
          builder: (context) => const ThoughtReshapingScreen(),
        ),
        (route) => false,
      );
    } catch (e) {
      print('Error saving thought record: $e');
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('保存记录失败: ${e.toString()}')),
      );
    }
  }

  Widget _buildCompletionView() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSection(
            title: '积极想法',
            content: widget.thoughtRecord.positiveThought ?? '',
            icon: HeroIcons.lightBulb,
            iconColor: Colors.yellow[700]!,
          ),
          const SizedBox(height: 24),
          _buildSection(
            title: '平衡观点',
            content: widget.thoughtRecord.balancedView ?? '',
            icon: HeroIcons.scale,
            iconColor: Colors.amber[700]!,
          ),
          const SizedBox(height: 24),
          _buildSection(
            title: '行动计划',
            content: widget.thoughtRecord.actionPlan ?? '',
            icon: HeroIcons.arrowTrendingUp,
            iconColor: Colors.purple[400]!,
          ),
          const SizedBox(height: 32),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  onPressed: _handleDiscardThought,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.grey[200],
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16),
                    ),
                    elevation: 0,
                  ),
                  child: Text(
                    '好的',
                    style: GoogleFonts.zcoolKuaiLe(
                      fontSize: 18,
                      color: AppColors.textPrimary,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: ElevatedButton(
                  onPressed: _handleSaveThought,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.primary,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16),
                    ),
                    elevation: 0,
                  ),
                  child: Text(
                    '记录此想法',
                    style: GoogleFonts.zcoolKuaiLe(
                      fontSize: 18,
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_isCompleted) {
      return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          title: Text(
            '反思总结',
            style: GoogleFonts.zcoolKuaiLe(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          centerTitle: true,
          leading: IconButton(
            icon: Icon(Icons.arrow_back, color: AppColors.textPrimary),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ),
        body: _buildCompletionView(),
      );
    }

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        title: Text(
          '引导反思',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: AppColors.textPrimary),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      HeroIcon(
                        HeroIcons.cloud,
                        size: 24,
                        style: HeroIconStyle.solid,
                        color: Colors.blueGrey,
                      ),
                      const SizedBox(width: 8),
                      Text(
                        '消极想法',
                        style: GoogleFonts.zcoolKuaiLe(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  Text(
                    widget.thoughtRecord.thought,
                    style: GoogleFonts.zcoolKuaiLe(
                      fontSize: 18,
                      color: AppColors.textPrimary,
                      height: 1.5,
                    ),
                  ),
                ],
              ),
            ),
            if (_questionAnswers.isNotEmpty) ...[
              const SizedBox(height: 24),
              Text(
                '反思历程',
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 16),
              ..._questionAnswers.map(_buildHistoryItem).toList(),
            ],
            if (_currentQuestion != null && !_isLoading) ...[
              const SizedBox(height: 24),
              Text(
                _currentQuestion!,
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 18,
                  color: AppColors.textPrimary,
                  height: 1.5,
                ),
              ),
              const SizedBox(height: 16),
              Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      blurRadius: 10,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: TextField(
                  controller: _answerController,
                  maxLines: 3,
                  decoration: InputDecoration(
                    hintText: '在这里输入你的回答...',
                    hintStyle: GoogleFonts.zcoolKuaiLe(
                      color: AppColors.textSecondary,
                    ),
                    contentPadding: const EdgeInsets.all(16),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(16),
                      borderSide: BorderSide.none,
                    ),
                    filled: true,
                    fillColor: Colors.white,
                  ),
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                    color: AppColors.textPrimary,
                  ),
                ),
              ),
            ],
            if (_isLoading) ...[
              const SizedBox(height: 24),
              Center(
                child: Column(
                  children: [
                    const CircularProgressIndicator(),
                    const SizedBox(height: 16),
                    Text(
                      '正在思考中...',
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 16,
                        color: AppColors.textSecondary,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
      ),
      bottomNavigationBar: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: ElevatedButton(
            onPressed: _isLoading ? null : _submitAnswer,
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.primary,
              padding: const EdgeInsets.symmetric(vertical: 16),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
              ),
              elevation: 0,
            ),
            child: _isLoading
                ? const SizedBox(
                    height: 24,
                    width: 24,
                    child: CircularProgressIndicator(
                      color: Colors.white,
                      strokeWidth: 2,
                    ),
                  )
                : Text(
                    '下一步',
                    style: GoogleFonts.zcoolKuaiLe(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
          ),
        ),
      ),
    );
  }
} 